﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using CommerceOne.Domains.Entities;
using CommerceOne.Domains.EntityExtentions;
using CommerceOne.Domains.Repositories;

namespace CommerceOne.Domains.SqlRepositories
{
    [NotMapped]
   public class SqlCategoryRepository : ICategoryRepository
    {
       private readonly EfDbContext _sqlContext = new EfDbContext();

       /// <summary>
       /// Gets all.
       /// </summary>
       /// <returns></returns>
       public List<Category> GetAll()
       {
           List<Category> list = this._sqlContext.Categories.ToList();
           this.UpdateProductCount(list);
           return list;
       }

       /// <summary>
       /// Gets the by id.
       /// </summary>
       /// <param name="id">The id.</param>
       /// <returns></returns>
       public Category GetById(int id)
       {
           return this._sqlContext.Categories.Where(p=>p.Id == id).FirstOrDefault();
       }

       /// <summary>
       /// Gets the by parent id.
       /// </summary>
       /// <param name="parentId">The parent id.</param>
       /// <returns></returns>
       public List<Category> GetByParentId(int? parentId)
       {
           List<Category> list = this._sqlContext.Categories.Where(p => !p.ParentId.HasValue).ToList();
           this.UpdateProductCount(list);
           return list;
       }

       /// <summary>
       /// Updates the product count.
       /// </summary>
       /// <param name="categoryList">The category list.</param>
        public void UpdateProductCount(List<Category> categoryList)
        {
            foreach (var item in categoryList)
            {
                GetProductCount(item);
            }
        }

        /// <summary>
        /// Gets the product count.
        /// </summary>
        /// <param name="category">The category.</param>
        public void GetProductCount(Category category)
        {
            category.ProductCount = category.Products == null ? 0 : category.Products.Count;
            if (category.ChildCategory == null || category.ChildCategory.Count == 0) return; // category.ProductCount;

            int count = 0;
            foreach (var child in category.ChildCategory)
            {
                GetProductCount(child);
                count += child.ProductCount;
            }
            category.ProductCount += count;
            return;// category.ProductCount;
        }
    }
}
